#微信登录
import secrets
import string

from fastapi import HTTPException
import requests
from common.config.env import H5LoginConfig, XcxLoginConfig

class WxLoginUtil:
  @classmethod
  async def xcxlogin(cls, wx_code):
      app_id = XcxLoginConfig.xcx_app_id
      app_secret = XcxLoginConfig.xcx_app_secret
      if not wx_code:
          raise HTTPException(status_code=400, detail="缺少 code 参数")
      url = f"https://api.weixin.qq.com/sns/jscode2session?appid={app_id}&secret={app_secret}&js_code={wx_code}&grant_type=authorization_code"
      response = requests.get(url)
      data = response.json()
      print(data)
      if 'openid' not in data:
          raise HTTPException(status_code=500, detail="微信接口调用失败")
      return data
  @classmethod
  async def     H5Login(cls, code):
      app_id = H5LoginConfig.h5_app_id
      app_secret = H5LoginConfig.h5_app_secret
      if not code:
          raise HTTPException(status_code=400, detail="Code is required")
      try:
          # 构建请求 URL
          url = f"https://api.weixin.qq.com/sns/oauth2/access_token?appid={app_id}&secret={app_secret}&code={code}&grant_type=authorization_code"

          # 发送请求
          response = requests.get(url)
          response.raise_for_status()  # 检查请求是否成功

          # 解析响应
          result = response.json()

          if 'errcode' in result and result['errcode'] != 0:
              raise HTTPException(status_code=400, detail=result['errmsg'])

          access_token = result.get("access_token")
          openid = result.get("openid")

          # 获取用户详细信息
          user_info_url = f"https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}&lang=zh_CN"
          user_info_response = requests.get(user_info_url)
          user_info_response.raise_for_status()  # 检查请求是否成功
          user_info = user_info_response.json()
          return user_info
      except requests.RequestException as e:
          raise HTTPException(status_code=500, detail=f"Error fetching session key: {e}")


